package ar.edu.itba.it.pdc.app.admin;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import ar.edu.itba.it.pdc.app.Madonna3;
import ar.edu.itba.it.pdc.app.config.mapping.User;

public class AdministrationService implements Runnable {

	private final ServerSocket server;
	private final Map<String, String> users = new HashMap<String, String>();
	
	public AdministrationService(final int port, final int backlog) throws IOException {
		
		for(User u : Madonna3.getApp().getSettings().getAdmin().getUsers()) {
			this.users.put(u.getUsername(), u.getPassword());
		}
		this.server = new ServerSocket(port, backlog);
		Madonna3.log.info("Madonna3 Admin Service started in: " + this.server.getInetAddress().getHostAddress() + ":" + port);
		
	}

	public void run() {
		try {
			while(true) {
				final Socket socket = server.accept();
				new Thread(new AdminSession(this, socket)).start();
			}
		} catch(IOException e){
			throw new RuntimeException(e);
		}
	}

	public boolean login(String username, String password) {
		return users.containsKey(username) && users.get(username).equals(password);
	}
	
}
